<template>
	<view class="my-posts-page">
		<!-- 顶部导航 -->
		<!-- 雪花 Canvas 背景 -->
		<canvas canvas-id="snow-canvas" class="snow-canvas"></canvas>
		<!-- 内容列表 -->
		<scroll-view scroll-y class="post-list" refresher-enabled :refresher-triggered="refreshing"
			@refresherrefresh="onRefresh">
			<!-- 空状态 -->
			<view v-if="posts.length === 0 && !loading" class="empty-state">
				<image src="/static/images/empty-post.png" mode="aspectFit" class="empty-image"></image>
				<text class="empty-text">你还没有发布过内容</text>
				<button class="publish-btn" @click="goToPublish">去发布</button>
			</view>

			<!-- 内容卡片 -->
			<view v-for="(item, index) in posts" :key="index" class="post-card">
				<!-- 顶部信息 -->
				<view class="card-header">
					<text class="category" :style="{color: getCategoryColor(item.category)}">
						{{item.category}}
					</text>
					<text class="time">{{item.created_at}}</text>
					<view class="status" v-if="item.status === 0">
						审核中
					</view>
				</view>

				<!-- 内容预览 -->
				<view class="content-preview" @click="viewDetail(item.id)">
					<text class="content-text">{{item.content}}</text>

					<!-- 多媒体预览 -->
					<view class="media-preview">
						<!-- 图片预览 -->
						<view v-if="item.images && item.images.length > 0" class="image-preview">
							<image :src="item.images[0].url" mode="widthFix"></image>
							<text v-if="item.images.length > 1" class="image-count">
								+{{item.images.length - 1}}
							</text>
						</view>

						<!-- 视频预览 -->
						<view v-else-if="JSON.parse(item.video_url)" class="video-preview">
							<video :src="JSON.parse(item.video_url)" ></video>
							<uni-icons type="videocam-filled" size="20" color="#fff" class="video-icon"></uni-icons>
						</view>
					</view>
				</view>

				<!-- 互动数据 -->
				<view class="interaction-data">
					<view class="data-item">
						<uni-icons type="eye" size="16" color="#999"></uni-icons>
						<text>{{item.view_count || 0}}</text>
					</view>
					<view class="data-item" @click="viewComments(item.id)">
						<uni-icons type="chat" size="16" color="#999"></uni-icons>
						<text>{{item.comment_count || 0}}</text>
					</view>
					<view class="data-item">
						<uni-icons type="heart" size="16" :color="item.liked ? '#ff4d6d' : '#999'"></uni-icons>
						<text>{{item.like_count || 0}}</text>
					</view>

					<!-- 操作按钮 -->
					<view class="action-btns">
						<button class="action-btn delete-btn" @click.stop="deletePost(item.id, index)">删除</button>
						<!-- <button open-type="share" class="action-btn share-btn" @click.stop="sharePost(item)">分享</button> -->
					</view>
				</view>
			</view>

			<!-- 加载更多 -->
			<view class="load-more">
				<text v-if="loading">加载中...</text>
				<text v-else-if="noMore">没有更多了</text>
			</view>
		</scroll-view>
		<!-- 评论列表弹窗 -->
		<uni-popup ref="commentPopup" type="bottom" :mask-click="true">
		  <view class="comment-popup">
		    <view class="popup-header">
		      <text class="popup-title">评论列表</text>
		      <uni-icons 
		        type="close" 
		        size="24" 
		        @click="closeCommentPopup"
		      ></uni-icons>
		    </view>
		    
		    <scroll-view 
		      scroll-y 
		      class="comment-list"
		      :scroll-top="scrollTop"
		      :scroll-with-animation="true"
		      :refresher-enabled="true"
		      :refresher-triggered="refreshingComments"
		      @refresherrefresh="refreshComments"
		      @scrolltolower="loadMoreComments"
		    >
		      <view  style="padding-bottom: 60px; padding-left: 25rpx;padding-right: 25rpx;margin-bottom: 60px;">
		      	<!-- 加载更多提示 -->
		      	<view class="loading-more" v-if="loadingMoreComments">
		      	  <uni-icons type="spinner-cycle" size="18" color="#999" class="loading-icon"></uni-icons>
		      	  <text>加载中...</text>
		      	</view>
		      	
		      	<!-- 评论列表 -->
		      	<view 
				  v-for="(comment, index) in currentComments" 
				  :key="comment.id"
				  
				>
				 <view class="comment-item">
					 <image
					   :src="comment.avatar || '/static/default_avatar.jpg'"
					   class="comment-avatar"
					 ></image>
					 <view class="comment-content" @click="commentNickname(comment)">
					   <view class="comment-user" style="display: flex;justify-content: space-between;">
						 <text class="username" >{{comment.nickname}}</text>
						 <text class="time">{{comment.created_at}}</text>
					   </view>
					   <text class="comment-text">{{comment.content}}</text>
					 </view>
				 </view>
				  <!-- 回复或评论 -->
				  <view  v-for="(item, index1) in comment.children" 
				  :key="item.id" class="comment-item" >
						<image
						  :src="item.avatar || '/static/default_avatar.jpg'"
						  class="comment-avatar"
						></image>
						<view class="comment-content" >
						  <view class="comment-user" @click="commentNickname(item)" style="display: flex;justify-content: space-between;">
							<text class="username" >{{item.nickname}}</text>
							<text class="time">{{item.created_at}}</text>
						  </view>
						  <text class="comment-text">{{item.content}}</text>
						</view>
				  </view>
				</view>
		      	
		      	<!-- 没有更多提示 -->
		      	<view v-if="noMoreComments" class="no-more">
		      	  <text>没有更多评论了</text>
		      	</view>
		      	
		      	<!-- 空状态 -->
		      	<view v-if="currentComments.length === 0 && !loadingComments" class="empty-comments">
		      	  <text>暂无评论</text>
		      	</view>
		      </view>
		    </scroll-view>
		    
		    <view class="comment-input-area">
		      <input 
		        v-model="newComment" 
		        placeholder="回复评论..." 
		        class="comment-input"
		        @confirm="sendComment"
		      />
		      <button 
		        class="send-btn"
		        :disabled="!newComment.trim()"
		        @click="sendComment"
		      >发送</button>
		    </view>
		  </view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				posts: [],
				loading: false,
				refreshing: false,
				noMore: false,
				page: 1,
				pageSize: 10,
			
				loadingComments: false,
				currentPostId: null,
				currentComments: [],
				newComment: '',
				loadingComments: false,
				refreshingComments: false,
				loadingMoreComments: false,
				noMoreComments: false,
				commentPage: 1,
				commentPageSize: 10,
				scrollTop: 0
			}
		},
		onShow() {
			this.loadPosts(true)
		},
		onLoad() {
			this.getmylist()
		},
		onReady() {
			this.initSnowEffect();
		},
		methods: {
			save(){
				uni.navigateTo({
					url:'/pages/post/create'
				})
			},
			async getmylist(){
				const res = await this.$api.get('/Confessions/mylist')
				console.log('dada',res)
				if(res.data.code == 200) {
					this.posts = res.data.data
				}
			},
			// 模拟雪花特效
			initSnowEffect() {
				const sys = uni.getSystemInfoSync();
				const W = sys.windowWidth;
				const H = sys.windowHeight;
				const ctx = uni.createCanvasContext('snow-canvas', this);
			
				const snowflakes = [];
				for (let i = 0; i < 40; i++) {
					snowflakes.push({
						x: Math.random() * W,
						y: Math.random() * H,
						r: Math.random() * 3 + 1,
						d: Math.random() * 2 + 1
					});
				}
			
				const draw = () => {
					ctx.clearRect(0, 0, W, H);
					ctx.setFillStyle('rgba(255,255,255,0.9)');
					ctx.beginPath();
					snowflakes.forEach(flake => {
						ctx.moveTo(flake.x, flake.y);
						ctx.arc(flake.x, flake.y, flake.r, 0, Math.PI * 2);
					});
					ctx.fill();
					snowflakes.forEach(flake => {
						flake.y += flake.d;
						flake.x += Math.sin(flake.y / 20) * 0.8;
						if (flake.y > H) {
							flake.y = 0;
							flake.x = Math.random() * W;
						}
					});
					ctx.draw();
					// #ifdef H5
					requestAnimationFrame(draw);
					// #endif
					// #ifdef MP-WEIXIN
					setTimeout(draw, 1000 / 60);
					// #endif
				};
			
				draw();
			},
			// 查看评论
			  async viewComments(postId) {
			    this.currentPostId = postId
			    this.commentPage = 1
			    this.noMoreComments = false
				
			    this.loadComments()
			  },
			  
			  // 加载评论
			  async loadComments() {
			    if (this.loadingComments) return
			    
			    this.loadingComments = true
			    try {
			      const res = await this.$api.get('Comment/index',{confession_id:this.currentPostId},true)
			      if(res.data.code === 200) {
				   this.currentComments = res.data.data
				   this.$refs.commentPopup.open()
				   this.loadingComments = false
				   this.refreshingComments = false
				   this.loadingMoreComments = false 
			      }
			      
			      
			    } catch (err) {
			      console.error('获取评论失败', err)
			      uni.showToast({
			        title: '获取评论失败',
			        icon: 'none'
			      })
			      this.loadingComments = false
			      this.refreshingComments = false
			      this.loadingMoreComments = false
			    }
			  },
			  
			  // 生成模拟评论数据
			  generateMockComments(page) {
			    const usernames = ['同学A', '同学B', '同学C', '同学D', '同学E']
			    const comments = [
			      '说的真好！我也深有同感~',
			      '毕业快乐！',
			      '期待下次见面！',
			      '加油！你是最棒的！',
			      '感谢分享！',
			      '太感动了😭',
			      '一起加油！',
			      '永远的朋友！',
				  '说的真好！我也深有同感~',
				  '毕业快乐！',
				  '期待下次见面！',
				  '加油！你是最棒的！',
				  '感谢分享！',
				  '太感动了😭',
				  '一起加油！',
				  '永远的朋友！',
				  '说的真好！我也深有同感~',
				  '毕业快乐！',
				  '期待下次见面！',
				  '加油！你是最棒的！',
				  '感谢分享！',
				  '太感动了😭',
				  '一起加油！',
				  '永远的朋友！'
			    ]
			    
			    return Array(this.commentPageSize).fill().map((_, i) => ({
			      id: page * 100 + i,
			      username: usernames[(page * 100 + i) % usernames.length],
			      avatar: `https://pic1.zhimg.com/80/v2-${Math.random().toString(36).substring(2)}_720w.webp`,
			      content: comments[(page * 100 + i) % comments.length],
			      time: Date.now() - (page * 86400000) - (i * 3600000)
			    }))
			  },
			  
			  // 刷新评论
			  refreshComments() {
			    this.refreshingComments = true
			    this.commentPage = 1
			    this.noMoreComments = false
			    this.loadComments()
			  },
			  
			  // 加载更多评论
			  loadMoreComments() {
			    if (this.noMoreComments || this.loadingMoreComments) return
			    this.loadingMoreComments = true
			    this.commentPage++
			    this.loadComments()
			  },
			  
			  // 发送评论
			  async sendComment() {
			    if (!this.newComment.trim()) return
			    
			    try {
			      // 模拟添加评论
			      const newComment = {
			        id: Date.now(),
			        username: '我',
			        avatar: '/static/images/my-avatar.png',
			        content: this.newComment,
			        time: Date.now()
			      }
			      
			      // 滚动到顶部显示最新评论
			      this.scrollTop = 0
			      this.currentComments.unshift(newComment)
			      
			      // 更新帖子评论数
			      const postIndex = this.posts.findIndex(p => p.id === this.currentPostId)
			      if (postIndex !== -1) {
			        this.posts[postIndex].commentCount += 1
			      }
			      
			      this.newComment = ''
			      uni.showToast({
			        title: '评论成功',
			        icon: 'success'
			      })
			      
			      // 实际项目中调用API发送评论
			      // await uni.request({
			      //   url: '/api/comment/add',
			      //   method: 'POST',
			      //   data: {
			      //     postId: this.currentPostId,
			      //     content: newComment.content
			      //   }
			      // })
			    } catch (err) {
			      console.error('评论失败', err)
			      uni.showToast({
			        title: '评论失败',
			        icon: 'none'
			      })
			    }
			  },
			  
			  // 关闭评论弹窗
			  closeCommentPopup() {
			    this.$refs.commentPopup.close()
			    this.newComment = ''
			    this.currentComments = []
			  },
			

			

			// 格式化评论时间
			formatCommentTime(timestamp) {
				const now = Date.now()
				const diff = now - timestamp
				const minute = 60 * 1000
				const hour = 60 * minute
				const day = 24 * hour

				if (diff < minute) return '刚刚'
				if (diff < hour) return `${Math.floor(diff / minute)}分钟前`
				if (diff < day) return `${Math.floor(diff / hour)}小时前`
				return `${Math.floor(diff / day)}天前`
			},
			// 加载帖子数据
			async loadPosts(refresh = false) {
				if (this.loading) return

				this.loading = true
				if (refresh) {
					this.page = 1
					this.noMore = false
				}

				try {
					// 这里替换为实际API调用
					// const res = await uni.request({
					//   url: '/api/user/posts',
					//   data: {
					//     page: this.page,
					//     pageSize: this.pageSize
					//   }
					// })

					// 模拟数据
					setTimeout(() => {
						const newData = Array(5).fill().map((_, i) => ({
							id: this.page * 100 + i,
							category: ['告白', '祝福', '寻人', '吐槽', '其他'][Math.floor(Math.random() *
								5)],
							content: this.getRandomContent(),
							images: Math.random() > 0.5 ? Array(Math.floor(Math.random() * 4) + 1)
								.fill().map(() =>
									`https://picsum.photos/300/200?random=${Math.random()}`
								) : [],
							video: Math.random() > 0.8 ?
								'https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4' :
								'',
							videoCover: 'https://picsum.photos/300/200?random=0.123',
							createTime: Date.now() - Math.floor(Math.random() * 86400000 * 7),
							viewCount: Math.floor(Math.random() * 500),
							commentCount: Math.floor(Math.random() * 100),
							likeCount: Math.floor(Math.random() * 200),
							liked: Math.random() > 0.5,
							status: Math.floor(Math.random() * 3) // 0:审核中,1:已通过,2:未通过
						}))

						if (refresh) {
							// this.posts = newData
						} else {
							// this.posts = [...this.posts, ...newData]
						}

						this.loading = false
						this.refreshing = false
						this.noMore = this.page > 2
					}, 800)
				} catch (err) {
					console.error('加载失败', err)
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
					this.loading = false
					this.refreshing = false
				}
			},

			// 下拉刷新
			onRefresh() {
				this.refreshing = true
				this.loadPosts(true)
			},

			// 获取随机内容
			getRandomContent() {
				const contents = [
					"四年的时光转瞬即逝，感谢有你们的陪伴！",
					"暗恋你很久了，今天终于鼓起勇气说出来！",
					"食堂二楼的小姐姐，你的笑容治愈了我一整天~",
					"寻找昨天在图书馆借我笔的同学，想当面说声谢谢！",
					"毕业季不说再见，我们江湖再会！",
					"有没有一起考研的小伙伴？互相监督学习呀~"
				]
				return contents[Math.floor(Math.random() * contents.length)]
			},

			// 格式化时间
			formatTime(timestamp) {
				const now = Date.now()
				const diff = now - timestamp
				const minute = 60 * 1000
				const hour = 60 * minute
				const day = 24 * hour
				const week = 7 * day

				if (diff < minute) return '刚刚'
				if (diff < hour) return `${Math.floor(diff / minute)}分钟前`
				if (diff < day) return `${Math.floor(diff / hour)}小时前`
				if (diff < week) return `${Math.floor(diff / day)}天前`
				return new Date(timestamp).toLocaleDateString()
			},

			// 获取分类颜色
			getCategoryColor(category) {
				const colors = {
					'告白': '#ff4d6d',
					'祝福': '#5cdbd3',
					'寻人': '#ff9c6e',
					'吐槽': '#ffc069',
					'其他': '#b37feb'
				}
				return colors[category] || '#69c0ff'
			},

			// 查看详情
			viewDetail(id) {
				uni.navigateTo({
					url: `/pages/index/noteDetail?id=${id}`
				})
			},

			// 删除帖子
			deletePost(id, index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这条内容吗？',
					success: (res) => {
						if (res.confirm) {
							// 实际调用删除API
							// uni.request({
							//   url: '/api/post/delete',
							//   method: 'POST',
							//   data: { id }
							// })

							// 模拟删除
							this.posts.splice(index, 1)
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							})
						}
					}
				})
			},

			// 分享帖子
			sharePost(item) {
				uni.share({
					title: item.content.length > 20 ? item.content.substring(0, 20) + '...' : item.content,
					summary: item.content,
					href: `/pages/confession/detail?id=${item.id}`,
					imageUrl: item.images && item.images.length > 0 ? item.images[0] : '',
					success: () => {
						uni.showToast({
							title: '分享成功',
							icon: 'success'
						})
					}
				})
			},

			// 返回
			goBack() {
				uni.navigateBack()
			},

			// 去发布页
			goToPublish() {
				uni.navigateTo({
					url: '/pages/post/create'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.snow-canvas {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 0;
		width: 100vw;
		height: 100vh;
		pointer-events: none;
	}
	/* 评论弹窗样式 */
	.comment-popup {
	  background-color: #fff;
	  border-top-left-radius: 16px;
	  border-top-right-radius: 16px;
	  padding-bottom: env(safe-area-inset-bottom);
	  max-height: 70vh;
	  display: flex;
	  flex-direction: column;
	  
	  .popup-header {
	    display: flex;
	    justify-content: space-between;
	    align-items: center;
	    padding: 16px;
	    border-bottom: 1px solid #f0f0f0;
	    flex-shrink: 0;
	    
	    .popup-title {
	      font-size: 18px;
	      font-weight: bold;
	      color: #333;
	    }
	  }
	  
	  .comment-list {
	    flex: 1;
	    height: 0; /* 关键样式，确保滚动 */
	    .loading-more, .no-more, .empty-comments {
	      display: flex;
	      justify-content: center;
	      align-items: center;
	      padding: 15px 0;
	      color: #999;
	      font-size: 14px;
	      
	      .loading-icon {
	        margin-right: 8px;
	        animation: rotating 1s linear infinite;
	      }
	    }
	    
	    .comment-item {
	      display: flex;
	      padding: 12px 0;
	      border-bottom: 1px solid #f5f5f5;
	      
	      .comment-avatar {
	        width: 40px;
	        height: 40px;
	        border-radius: 50%;
	        margin-right: 12px;
	        flex-shrink: 0;
	      }
	      
	      .comment-content {
	        flex: 1;
	        min-width: 0;
	        
	        .comment-user {
	          display: flex;
	          align-items: center;
	          margin-bottom: 4px;
	          
	          .username {
	            font-size: 15px;
	            font-weight: bold;
	            color: #333;
	            margin-right: 8px;
	            white-space: nowrap;
	            overflow: hidden;
	            text-overflow: ellipsis;
	          }
	          
	          .time {
	            font-size: 12px;
	            color: #999;
	            flex-shrink: 0;
	          }
	        }
	        
	        .comment-text {
	          font-size: 14px;
	          color: #333;
	          line-height: 1.5;
	          word-break: break-word;
	        }
	      }
	    }
	  }
	  
	  .comment-input-area {
	    display: flex;
	    padding: 12px 16px;
	    border-top: 1px solid #f0f0f0;
	    background-color: #fff;
	    flex-shrink: 0;
		background: #fff;
		z-index: 100;
	    
	    .comment-input {
	      flex: 1;
	      height: 36px;
	      padding: 0 12px;
	      background-color: #f5f5f5;
	      border-radius: 18px;
	      font-size: 14px;
	      margin-right: 10px;
	    }
	    
	    .send-btn {
	      height: 36px;
	      line-height: 36px;
	      padding: 0 16px;
	      background-color: #74b9ff;
	      color: #fff;
	      border-radius: 18px;
	      font-size: 14px;
	      border: none;
	      
	      &::after {
	        border: none;
	      }
	      
	      &[disabled] {
	        background-color: #ccc;
	      }
	    }
	  }
	}
	
	@keyframes rotating {
	  from { transform: rotate(0deg); }
	  to { transform: rotate(360deg); }
	}
	

	.my-posts-page {
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		// background-color: #f8f9fa;
		background: linear-gradient(to right, #c3f0f7, #fff7d6);

		.header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 15px 20px;
			background-color: #fff;
			border-bottom: 1px solid #f0f0f0;

			.title {
				font-size: 18px;
				font-weight: bold;
				color: #333;
			}
		}

		.post-list {
			flex: 1;
			height: calc(100vh - 20rpx);
			.empty-state {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding-top: 100px;

				.empty-image {
					width: 200px;
					height: 200px;
					opacity: 0.6;
					margin-bottom: 20px;
				}

				.empty-text {
					font-size: 16px;
					color: #999;
					margin-bottom: 30px;
				}

				.publish-btn {
					width: 200px;
					height: 40px;
					line-height: 40px;
					background: linear-gradient(90deg, #a18cd1, #fbc2eb);
					color: #fff;
					border-radius: 20px;
					font-size: 16px;
					border: none;

					&::after {
						border: none;
					}
				}
			}

			.post-card {
				margin: 12px;
				padding: 15px;
				background-color: #fff;
				border-radius: 12px;
				box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

				.card-header {
					display: flex;
					align-items: center;
					margin-bottom: 12px;
					font-size: 12px;

					.category {
						font-weight: bold;
						margin-right: 10px;
					}

					.time {
						color: #999;
						margin-right: 10px;
					}

					.status {
						padding: 2px 6px;
						background-color: #fffbe6;
						color: #faad14;
						border-radius: 4px;
						font-size: 11px;
					}
				}

				.content-preview {
					margin-bottom: 15px;

					.content-text {
						font-size: 15px;
						line-height: 1.6;
						color: #333;
						margin-bottom: 10px;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 3;
						overflow: hidden;
					}

					.media-preview {
						.image-preview {
							position: relative;
							height: 120px;
							border-radius: 8px;
							overflow: hidden;

							image {
								width: 100%;
								height: 100%;
								object-fit: cover;
							}

							.image-count {
								position: absolute;
								right: 8px;
								bottom: 8px;
								background-color: rgba(0, 0, 0, 0.5);
								color: #fff;
								font-size: 12px;
								padding: 2px 8px;
								border-radius: 10px;
							}
						}

						.video-preview {
							position: relative;
							height: 120px;
							border-radius: 8px;
							overflow: hidden;

							video {
								width: 100%;
								height: 100%;
								object-fit: cover;
							}

							.video-icon {
								position: absolute;
								left: 8px;
								bottom: 8px;
								background-color: rgba(0, 0, 0, 0.5);
								padding: 4px;
								border-radius: 50%;
							}
						}
					}
				}

				.interaction-data {
					display: flex;
					align-items: center;
					padding-top: 10px;
					border-top: 1px solid #f5f5f5;

					.data-item {
						display: flex;
						align-items: center;
						margin-right: 15px;
						color: #666;
						font-size: 13px;

						text {
							margin-left: 4px;
						}
					}

					.action-btns {
						flex: 1;
						display: flex;
						justify-content: flex-end;

						.action-btn {
							height: 28px;
							line-height: 28px;
							padding: 0 12px;
							font-size: 12px;
							border-radius: 14px;
							margin-left: 8px;
							border: none;

							&::after {
								border: none;
							}
						}

						.delete-btn {
							background-color: #fff2f0;
							color: #ff4d4f;
						}

						.share-btn {
							background-color: #f0f7ff;
							color: #1890ff;
						}
					}
				}
			}

			.load-more {
				text-align: center;
				padding: 15px;
				color: #999;
				font-size: 14px;
			}
		}
	}
</style>